package com.aggron.concurrency.examples.singeton;

import com.aggron.concurrency.annotations.NotThreadSafe;

/**
 *
 * @author LR2SD
 * @description 懒汉模式--双重同步锁的单例模式
 * @date 2018-06-10 15:52
 */
@NotThreadSafe
public class SingletonExample3 {

    private static SingletonExample3 singletonExample1=null;

    private SingletonExample3(){

    }

    //1、memory =allocate()分配对象内存空间
    //2、ctorInstance初始化对象
    //3、instance=memory设置Instance指向刚分配的内存空间

    //jvm和cpu优化发生了指令重排序
    //1、memory =allocate()分配对象内存空间
    //3、instance=memory设置Instance指向刚分配的内存空间
    //2、ctorInstance初始化对象
    /**
     * 静态工场模式
     * @return
     */
    public static  SingletonExample3 getInstance(){
        if(singletonExample1==null){ //B
            synchronized (SingletonExample3.class){//同步锁
                if(singletonExample1==null){//双重判断
                    singletonExample1=new SingletonExample3();//A -3
                }
            }

        }
        return singletonExample1;
    }
}
